package org.ligson.fwc.api.util.date;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

import java.util.Date;

/***
 * 日期转换器：支持的格式
 */
public class DateConverter implements Converter<String, Date> {
    private static Logger logger = LoggerFactory.getLogger(DateConverter.class);
    private static String[] supportDateFmt = new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "yyyy-MM"};

    @Override
    public Date convert(String source) {
        for (String fmt : supportDateFmt) {
            try {
                return DateUtils.parseDate(source, fmt);
            } catch (Exception e) {
                continue;
            }
        }
        try {
            long time = Long.parseLong(source);
            return new Date(time);
        } catch (Exception e) {
            logger.error("不支持的日期格式:{}", source);
        }
        return null;
    }
}
